package com.atguigu.lease.web.admin.custom.interceptor;

import com.atguigu.lease.common.contest.LoginUser;
import com.atguigu.lease.common.contest.LoginUserContest;
import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
@Component
public class AuthenticationInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

    String accessToken = request.getHeader("access_token");
        if(accessToken==null) {
            throw new LeaseException(ResultCodeEnum.ADMIN_LOGIN_AUTH);
        }else {
            //解析是否过期
            Claims claims = JwtUtil.parseToken(accessToken);
            Long userId = claims.get("userId", Long.class);
            String userName = claims.get("userName", String.class);
//            //负载放到请求域当中
//            request.setAttribute("userId",userId);
            //把负载数据保存到当前线程中
            LoginUserContest.setUser(new LoginUser(userId,userName));

        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
LoginUserContest.removeUser();
    }
}
